<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入名称或账号"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"
		  :data="tableDatas" - 表格数据
		  v-loading="listLoading" - 加载圈
		  @selection-change="handleSelectionChange" - 选项改变触发 - 批量删除
		  highlight-current-row - 当前行高亮
		-->
		<el-table :data="tableDatas" v-loading="listLoading"
              @selection-change="handleSelectionChange"
              highlight-current-row
			style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="70" label="序号">
			</el-table-column>
			<el-table-column prop="realName" label="真实姓名" width="120">
			</el-table-column>
			<el-table-column prop="userName" label="登录账号" width="120">
			</el-table-column>
			<el-table-column prop="phone" label="手机号" width="150">
			</el-table-column>
      <el-table-column label="头像" width="150">
        <template scope="scope">
          <img :src="scope.row.avatar" height="50"/>
        </template>
      </el-table-column>
			<el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="remark" label="备注" width="300" show-overflow-tooltip>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
      <!--
        :current-page="currentPage"  - 当前页
        :total="totals" - 总条数
        :page-size="pageSize" - 每页显示的条数
        background - 背景
        @current-change="handleCurrentChange" - 当前页改变触发
        @size-change="handleSizeChange" - 每页显示条数改变的时候触发
        layout="total, sizes, prev, pager, next, jumper"
      -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
				:page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" background
				:total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加或修改界面-->
    <!--
      :close-on-click-modal="false" - 点击屏幕关闭对话框功能关闭，点x才关闭
    -->
		<el-dialog title="保存用户" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="用户名称" prop="userName">
					<el-input v-model="saveForm.userName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="真实姓名">
					<el-input v-model="saveForm.realName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机号码" prop="phone">
					<el-input v-model="saveForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱地址">
					<el-input v-model="saveForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="登录密码" v-if="saveForm.id == null" prop="password">
					<el-input type="password" v-model="saveForm.password" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="头像">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/minio"
                     name="file"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :on-exceed="exceed"
                     :file-list="fileList"
                     :limit=1
                     accept=".jpg,.jpeg,.png,.gif"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传指定类型的图片</div>
          </el-upload>
        </el-form-item>
				<el-form-item label="备注信息">
					<el-input v-model="saveForm.remark" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

export default {
	data() {
		return {
			//1.分页查询相关数据
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条

			tableDatas: [], //当前页数据
			listLoading: false, //加载圈

			//2.高级查询相关数据
			keyword: '',

			//3.删除相关数据

			//4.批量删除相关数据
			sels: [], //存储多选记录

			//5.添加和修改相关数据
			saveFormVisible: false,
			saveForm: {
				id: null,
				userName: '',
				realName: '',
				email: '',
				password: '', //后端需要通过md5加密
				remark: '',
        avatar: '',
				phone: ''
				//avatar头像 - 前端没有传递 - 需要文件上传
				//logininfo_id - 后端业务生成
        //salt - 盐值
			},

			//6.添加和修改校验规则-表单项校验
			saveFormRules: {
        userName: [
					{ required: true, message: '请输入用户名称', trigger: 'blur' }
				],
				phone: [
					{ required: true, message: '请输入电话号码', trigger: 'blur' }
				],
				password: [
					{ required: true, message: '请输入登录密码', trigger: 'blur' }
				]
			},

      fileList: []

		}
	},
	methods: {
		//1.分页查询相关方法
		//1.1.获取列表数据
		getTableData() {
      //显示加载圈
      this.listLoading = true;
      var params = {
        "currentPage": this.currentPage,
        "pageSize":this.pageSize,
        'keyword': this.keyword
      }
      this.$http.post("/user",params).then(res=>{
        //res.data是axios获取数据的固定格式。list和total是后端响应的数据-PageInfo中
        this.tableDatas = res.data.list;
        this.totals = res.data.total;
        //关闭加载圈
        this.listLoading = false;
      })
		},
		//1.2.选择第几页时触发
		handleCurrentChange(currentPage) {
      this.currentPage = currentPage;//1 - 2
      this.getTableData();
		},
		//1.3.选择每页显示记录条数时触发
		handleSizeChange(pageSize) {
			this.pageSize = pageSize; //5 - 10
      this.getTableData();
		},

		//2.高级查询相关方法
		keywordQuery() {
      this.currentPage = 1;
      this.getTableData();
		},

		//3.删除相关方法
		handleDel(row) {
      this.$confirm('确定要删除当前数据吗?', '提示', {
        type: 'warning'
      }).then(() => {//点击确认框的确定执行then里面的代码
        this.$http.delete("/user/"+row.id).then(res=>{ //AjaxResult
          if(res.data.success){
            this.$message.success("删除成功");
            this.getTableData();
          }else{
            this.$message.error("服务器异常【500】");
          }
        }).catch(res=>{
          this.$message.error("网络异常【404,400】");
        })
      }).catch(() => { //点击确认框的取消邹catch，取消可以什么都不做
      });
		},

		//4.批量删除相关方法
		//4.1.选项改变时触发
		handleSelectionChange(val) {
      //val = 被选中的对象组成的数组
      this.sels = val;
		},

		//4.2.批量删除
		handlePatchDel() {
      this.$confirm('确定要删除选中数据吗?', '提示', {
        type: 'warning'
      }).then(() => {//点击确认框的确定执行then里面的代码
        let ids = this.sels.map(obj => obj.id);//[1,2,3]
        this.$http.patch("/user",ids).then(res=>{ //AjaxResult
          if(res.data.success){
            this.$message.success("删除成功");
            this.getTableData();
          }else{
            this.$message.error("服务器异常【500】");
          }
        }).catch(res=>{
          this.$message.error("网络异常【404,400】");
        })
      }).catch(() => { //点击确认框的取消邹catch，取消可以什么都不做
      });
		},

		//5.添加和修改相关方法
		//5.1.点击添加弹出对话框
		handleAdd() {
      //重置表单
      this.saveForm = {
        id: null,
        userName: '',
        realName: '',
        email: '',
        password: '', //后端需要通过md5加密
        remark: '',
        avatar: '',
        phone: ''
      }
      //清空fileList和articlePic
      this.fileList=[];
      //显示对话框
      this.saveFormVisible = true;
		},
		//5.2.点击修改弹出对话框
		handleEdit(row) {
      //回显：不能使用this.saveForm=row，因为两个引用指向一个对象，任何一个改了，另外一个也会改变
      this.saveForm = Object.assign({}, row);
      //Pic在数据库：http://60.204.187.34:9090/java1117/1708932861299.png
      this.fileList=[];
      if(this.saveForm.avatar){
        this.fileList.push({'url':this.saveForm.avatar})
      }
      //显示对话框
      this.saveFormVisible = true;
		},
		//5.3.提交表单数据操作数据库
		saveSubmit() {
      //所有表单项校验通过才能提交，只要有一个表单项校验不通过就不能提交
      this.$refs.saveForm.validate((valid) => {
        if(valid){
          this.$http.put("/user",this.saveForm).then(res=>{
            if(res.data.success){
              this.$message.success("操作成功");
              this.saveFormVisible = false;
              this.getTableData();
            }else{
              this.$message.error("服务器异常【500】");
              this.saveFormVisible = false;
            }
          }).catch(res=>{
            this.$message.error("网络异常【404,400】");
          })
        }else{
          this.$message.error("表单校验失败");
        }
      })
		},

    //删除之后的钩子
    handleRemove(file, fileList) {
      //点击删除的时候要获取文件名称，然后调用后端的删除接口
      var fileName = file.name;
      this.$http.delete("/minio/"+fileName).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功");
          //清空fileList和articlePic
          this.fileList=[];
          this.saveForm.avatar='';
        }else{
          this.$message.error("删除失败");
        }
      })
    },
    //上传成功之后的钩子
    handleSuccess(response, file, fileList) {
      //上传成功之后将文件名获取出来，拼接上minio的地址 给 articlePic复制
      var filePath =  "http://60.204.187.34:9090/java1210/"+response.obj;
      this.saveForm.avatar = filePath;
      //维护fileList - 前端显示图片的
      if(this.saveForm.avatar){
        this.fileList.push({'name':response.obj,'url':filePath})
      }
    },
    //超出个数之后的钩子
    exceed() {
      this.$message.error("最多只能上传一个文件")
    },
	},
	mounted() {
		this.getTableData();
	}
}

</script>

<style scoped></style>
